package com.link.base.tencent.corpwx.login.controller;

import com.link.core.basic.service.BasicServiceException;
import com.link.core.cllog.LCLogger;
import com.link.base.tencent.corpwx.login.service.CorpWxLoginService;
import com.link.base.wechat.thirdparty.service.ThirdPartyAuthService;
import com.link.core.util.IpUtil;
import com.link.core.util.RedisUtil;
import com.link.base.core.basic.util.YmlConstants;
import com.link.core.util.redisclient.LinkRedisClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 企业微信登录授权
 *
 * @author 欧阳振强
 */
@Controller("corpWxLoginController")
@RequestMapping("/link/corpwx/user_login")
public class LoginController {
    /**
     * 判断链接中是否有问号
     */
    private static final String QUESTION_MARK = "?";
    @Resource
    private CorpWxLoginService corpWxLoginService;
    @Resource
    private ThirdPartyAuthService thirdPartyAuthService;

    /**
     * 接收url，通过服务端重定向企业微信授权链接获取code，并将code拼接到url，执行重定向操作
     *
     * @author 欧阳振强
     * @date 2019/03/11 10:45
     */
    @GetMapping(value = "/redirect", name = "重定向企业微信授权入口")
    public void redirect(HttpSession session,
                         HttpServletRequest request, HttpServletResponse response) throws Exception {
        LinkRedisClient j = null;
        try {
            j = RedisUtil.getJedis();
            // 真正需要打开的链接
            String redirectUrl = request.getParameter("url");
            if (StringUtils.isBlank(redirectUrl)) {
                throw new BasicServiceException("重定向Url不能为空！");
            }
            // 企业微信Id
            String corpId = request.getParameter("corpId");
            if (StringUtils.isBlank(corpId)) {
                throw new BasicServiceException("企业微信Id不能为空！");
            }
            // 缓存重定向地址信息
            String crmRedisKey = thirdPartyAuthService.createCrmToken();
            j.hset(crmRedisKey, "corpId", corpId);
            j.hset(crmRedisKey, "redirectUrl", redirectUrl);
            // 获取授权链接并重定向
            String redirectServerUrl = YmlConstants.getWxComponentAuthRedirectUrl() + "/link/corpwx/user_login/receiveCode";
            String loginAuthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?"
                + "appid=" + corpId + "&redirect_uri=" + redirectServerUrl + "&response_type=code&scope=snsapi_base&state="
                + crmRedisKey + "#wechat_redirect";
            response.sendRedirect(loginAuthUrl);
        } catch (Exception e) {
            LCLogger.withException(e);
        } finally {
            RedisUtil.returnResource(j);
        }
    }

    /**
     * 接收code并处理相关事项
     *
     * @author 欧阳振强
     * @date 2019/03/11 01:47
     */
    @GetMapping(value = "/receiveCode", name = "重定向企业微信授权处理code")
    public void receiveDevCode(HttpSession session,
                               HttpServletRequest request, HttpServletResponse response) throws Exception {
        String code = request.getParameter("code");
        String crmRedisKey = request.getParameter("state");
        try {
            LinkRedisClient j = RedisUtil.getJedis();
            String redirectUrl;
            try {
                redirectUrl = j.hget(crmRedisKey, "redirectUrl");
                String param = "code=" + code;
                if (redirectUrl.contains(QUESTION_MARK)) {
                    redirectUrl = redirectUrl + "&" + param;
                } else {
                    redirectUrl = redirectUrl + "?" + param;
                }
            } finally {
                j.del(crmRedisKey);
                RedisUtil.returnResource(j);
            }
            response.sendRedirect(redirectUrl);
        } catch (Exception e) {
            LCLogger.withException(e);
        }
    }

    /**
     * 前端使用code和agentId进行登录
     *
     * @author 欧阳振强
     * @date 2019/03/26 18:20
     */
    @GetMapping(value = "/loginByCode", name = "前端使用code和agentId进行登录")
    @ResponseBody
    public Map<String, Object> loginByCode(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        LCLogger.info().withMessageKey("login").withMessage("企业微信登录中..").flush();
        try {
            String code = request.getParameter("code");
            if (StringUtils.isBlank(code)) {
                throw new BasicServiceException("code参数为空！");
            }
            String agentId = request.getParameter("agentId");
            if (StringUtils.isBlank(agentId)) {
                throw new BasicServiceException("agentId参数为空！");
            }
            LCLogger.info().withMessageKey("login").withMessage("code => " + code + "，agentId => " + agentId).flush();
            // 登录
            String ip = IpUtil.getIpAddress(request);
            result = corpWxLoginService.loginByCode(code, agentId, ip);

        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

}
